package com.sitech.portal.util.excel;

import java.io.*;
import jxl.*;
import jxl.write.*;
import java.util.*;

public class ExcelBean {
	public ExcelBean() {
	}

	/**
	 * 导出excel
	 * @param os
	 * @param title	标题
	 * @param columnCNNames	列名
	 * @param keys	list中map的key
	 * @param list<map>	数据
	 * @return
	 * @throws Exception
	 */
	public String expordExcel(OutputStream os,String title,String[] columnCNNames,String[] keys, List<Map> list) throws Exception {
		jxl.write.WritableWorkbook wbook = Workbook.createWorkbook(os); // 建立excel文件
		jxl.write.WritableSheet wsheet = wbook.createSheet(title, 0); // sheet名称

		jxl.write.WritableFont wfont = new jxl.write.WritableFont(
				WritableFont.ARIAL, 16, WritableFont.BOLD, false,
				jxl.format.UnderlineStyle.NO_UNDERLINE, jxl.format.Colour.BLACK);
		jxl.write.WritableCellFormat wcfFC = new jxl.write.WritableCellFormat(
				wfont);
		jxl.write.Label wlabel1;
		wlabel1 = new jxl.write.Label(3, 0, title, wcfFC);

		wsheet.addCell(wlabel1);
		wfont = new jxl.write.WritableFont(WritableFont.ARIAL, 14,
				WritableFont.BOLD, false,
				jxl.format.UnderlineStyle.NO_UNDERLINE, jxl.format.Colour.BLACK);
		wcfFC = new jxl.write.WritableCellFormat(wfont);
		
		for(int i=0;i<columnCNNames.length;i++){
			jxl.write.Label wlabe = new jxl.write.Label(i, 1, columnCNNames[i]);
			wsheet.addCell(wlabe);
		}
		
		if (list != null && list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				HashMap map = (HashMap) list.get(i);
				addCell(wsheet, map, keys, i);
			}
		}
		wbook.write(); // 写入文件
		wbook.close();
		os.close();
		return "success";
	}

	private void addCell(jxl.write.WritableSheet wsheet, HashMap map, String[] keys, int i)
			throws Exception, WriteException {
		int key0 = i + 1;
		i = i + 2;
		
		for(int j=0;j<keys.length;j++){
			jxl.write.Label wlabe1 = new jxl.write.Label(j, i, getStringByHM(map,keys[j]));
			wsheet.addCell(wlabe1);
		}
	}

	public String getStringByHM(HashMap map, String key) {
		String str = "";
		try {
			str = map.get(key).toString();
		} catch (Exception e) {
			// TODO: handle exception
		}
		return str;
	}
}
